import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide FormData, MultipartFile;
import 'package:high_help_apps/common/apis/v1/file.dart';
import 'package:high_help_apps/common/utils/toast.dart';
import 'package:high_help_apps/common/widgets/common/common_text_button.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:high_help_apps/common/entities/file/commodity_file_upload_result_entity.dart';
import 'life_help_add_shop_state.dart';

class LifeHelpAddShopLogic extends GetxController {
  final state = LifeHelpAddShopState();
  ImagePicker imagePicker = ImagePicker();
  bool isUploading = false;
  double currentProcessValue = 0;

  void uploadLocalImage() async {
    List<XFile>? tempPics = await imagePicker.pickMultiImage();
    if (state.imagePath != null) state.imagePath!.addAll(tempPics!);
    update();
    Get.back();
  }

  void uploadCameraImage() async {
    XFile? tempPic = await imagePicker.pickImage(source: ImageSource.camera);
    print(tempPic);
    state.imagePath!.add(tempPic!);
    update();
    Get.back();
  }

  void showDeleteImageDialog(BuildContext context, int index) async {
    await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("确定要删除吗"),
            actions: <Widget>[
              CommonTextButton(
                width: 65.w,
                title: '删除',
                onPressed: () {
                  toastInfo(msg: '删除成功');
                  state.imagePath!.removeAt(index);
                  update();
                  Get.back();
                },
                backgroundColor: Colors.red[400],
              ),
              CommonTextButton(
                  title: '取消',
                  width: 65.w,
                  onPressed: () {
                    Get.back();
                  }),
            ],
          );
        });
  }

  void uploadAllPicture() async {
    for (int i = 0; i < state.imagePath!.length; i++) {
      String path = state.imagePath![i].path.substring(
          state.imagePath![i].path.lastIndexOf("/") + 1,
          state.imagePath![i].path.length);
      FormData data = FormData.fromMap({
        "file": await MultipartFile.fromFile(state.imagePath![i].path, filename: path)
      });

      CommodityFileUploadResultEntity commodityFileUploadResultEntity = await FileAPI.sendCommodity(data);

      if(commodityFileUploadResultEntity.success == true) {
        currentProcessValue += (1 / (state.imagePath!.length + 1));
      }

    }
  }

  void releaseSecondCommodity() async {
    if(isUploading == false) {
      isUploading = true;
      update();
      uploadAllPicture();
    }
  }
}
